<?php

namespace core;

use application\webapp\config\StaticConfig;
use core\util\cache\Cache;
use core\util\cache\FileCacheDriver;
use core\util\Constant;
use Exception;
use stdClass;
use core\system\Session;

class CoreView {

    private $vars = array();
    protected $baseUrl;
    public $scriptClient;
    public $path;
    public $session;
    public $layout = '/layout/main';
    public $cache = [false, 'system', 'system', 1000];
    public $debug = true;
    private $caching;

    function __construct($baseUrl) {
        $this->baseUrl = $baseUrl;
        $this->caching = new Cache();
        $this->caching->addDriver('file', new FileCacheDriver());
        $this->session = new Session();
    }

    public function __set($index, $value) {
        $this->vars[$index] = $value;
    }

    public function genJavaScript($jsPath = null) {
        if ($jsPath != null && StaticConfig::javaScript()[$jsPath] != null) {
            $js = StaticConfig::javaScript()[$jsPath];
            $linkjs = "";
            if (!$this->debug) {
                $cachefile = 'upload/cache' . $jsPath;
                $cachetime = 360 * 24 * 60 * 60;
                if (!(file_exists($cachefile) && time() - $cachetime < filemtime($cachefile))) {
                    $jsContent = '';
                    foreach ($js as $include) {
                        $arrPath = CoreBase::readPathFile("application/webapp/static" . $include);
                        foreach ($arrPath as $file) {
                            if (!strpos($file, "/lib")) {
                                $jsContent .= file_get_contents($file);
                            } else {
                                $linkjs .= ($file != "") ? '<script type="text/javascript" language="JavaScript" src="' . $this->baseUrl . $file . '" ></script>' : "";
                            }
                        }
                    }
                    $jsContent = util\TextUtil::compress($jsContent);
                    $cached = fopen($cachefile, 'w') or exit("Không mở được file | url không tồn tại[bạn không có quyền w]");
                    fwrite($cached, $jsContent); //ob_get_contents()
                    fclose($cached);
                }
                $linkjs .= '<script type="text/javascript" language="JavaScript" src="' . $this->baseUrl . $cachefile . '" ></script>';
                $cacheLink = $this->caching->get('link', 'script', $cachetime);
                if (!$cacheLink) {
                    $this->caching->set('view/link', 'script', $linkjs);
                } else {
                    $linkjs = $cacheLink;
                }
            } else {
                foreach ($js as $include) {
                    $arrPath = CoreBase::readPathFile("application/webapp/static" . $include);
                    foreach ($arrPath as $file) {
                        $linkjs .= ($file != "") ? '<script type="text/javascript" language="JavaScript" src="' . $this->baseUrl . $file . '" ></script>' : "";
                    }
                }
            }
            return $linkjs;
        }
    }

    public function genStyleSheet($stylePath = null) {
        if ($stylePath != null && StaticConfig::css()[$stylePath] != null) {
            $css = StaticConfig::css()[$stylePath];
            $linkStyle = "";
            foreach ($css as $include) {
                $arrPath = CoreBase::readPathFile("application/webapp/static" . $include);
                foreach ($arrPath as $file) {
                    $linkStyle .= ($file != "") ? '<link type="text/css" rel="stylesheet" href="' . $this->baseUrl . $file . '" />' : "";
                }
            }
            return $linkStyle;
        }
    }

    public function render($path = null) {
        if ($this->layout == null) {
            $fileBody = $path;
        } else {
            $this->path = $path;
            $fileBody = $this->layout;
        }
        $this->loadView($fileBody);
    }

    public function loadView($fileBody = null) {
        $fileBody = 'application/webapp/view/' . Constant::$SECTION . $fileBody . '.php';
        if (!file_exists($fileBody)) {
            die('Invalid view file : ' . $fileBody);
        }
        ob_start();
        try {
            $this->cacheView($fileBody);
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
        echo ob_get_clean();
    }

    private function cacheView($file) {
        if ($this->cache[0] == true) {
            $this->cache[0] = false;
            ob_start(); // Bật buffer cho output
            $cData = $this->caching->get($this->cache[1], $this->cache[2], $this->cache[3]);
            if (!$cData) {
                extract($this->vars);
                require $file;
                $this->caching->set($this->cache[1], $this->cache[2], ob_get_contents());
            } else {
                echo $cData;
            }
            ob_end_flush(); // Dừng buffer, gửi nội dung đến trình duyệt
        } else {
            extract($this->vars);
            require $file;
        }
    }

    public function response($success = false, $message = '', $data = null) {
        if (!is_object($success)) {
            $object = new stdClass();
            $object->success = $success;
            $object->message = $message;
            $object->data = $data;
        } else {
            $object = $success;
        }
        echo json_encode($object);
        return false;
    }

}
